from werkzeug.security import generate_password_hash
from werkzeug.security import check_password_hash
from flask_login import UserMixin
import json
import uuid
from config import *
from flask_script import Manager
from  bterthird import db

# define profile.json constant, the file is used to
# save user name and password_hash
PROFILE_FILE = "profiles.json"
app = get_app()

manager = Manager(app)

class User(db.Model,UserMixin):
    __tablename__ = 'users'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    passwd = db.Column(db.String(300), nullable=False)


    @property
    def password(self):
        raise AttributeError('password is not a readable attribute')

    @password.setter
    def password(self, password):
        """save user name, id and password hash to json file"""
        self.password_hash = generate_password_hash(password)
        with open(PROFILE_FILE, 'w+') as f:
            try:
                profiles = json.load(f)
            except ValueError:
                profiles = {}
            profiles[self.username] = [self.password_hash,
                                       self.id]
            f.write(json.dumps(profiles))

    def verify_password(self, password):
        #print generate_password_hash(str(password),method="md5",salt_length=8)
        if self.passwd is None:
            return False
        return check_password_hash(self.passwd, str(password))

    def get_password_hash(self):
        """try to get password hash from file.

        :return password_hash: if the there is corresponding user in
                the file, return password hash.
                None: if there is no corresponding user, return None.
        """
        try:
            return User.query.filter(User.username == self.uname).first().passwd
        except IOError:
            return None
        except ValueError:
            return None
        return None

    def get_id(self):
        """get user id from profile file, if not exist, it will
        generate a uuid for the user.
        """
        if self.username is not None:
            return self.id
        return unicode(uuid.uuid4())

    @staticmethod
    def getUserByName(username):
        """get user id from profile file, if not exist, it will
        generate a uuid for the user.
        """
        if username is not None:
            try:
                return User.query.filter(User.username == username).first()
            except IOError:
                pass
            except ValueError:
                pass
        return unicode(uuid.uuid4())

    @staticmethod
    def get(user_id):
        """try to return user_id corresponding User object.
        This method is used by load_user callback function
        """
        if not user_id:
            return None
        try:
            return User.query.get(user_id)
        except:
            return None
        return None

if __name__ == '__main__':
    manager.run()